#include "WakeOnWan.hpp"
#include "utils/NetUtils.hpp"
#include "utils/Socket.hpp"

WakeOnWan::WakeOnWan()
{
}

WakeOnWan::~WakeOnWan()
{
}

int WakeOnWan::exec(int ac, char **av)
{
  if (ac != 3)
    {
      std::cerr << "usage: WakeOnWan host MAC" << std::endl;
      return 1;
    }
  if (!NetUtils::is_valid_mac(av[2]))
    {
      std::cerr << "Invalid MAC Address format" << std::endl;
      return 1;
    }
  return this->WakeUp(av[1], av[2]);
}

int WakeOnWan::WakeUp(const std::string &hostname, const std::string &mac)
{
  Socket s;
  
  if (!s.connect(hostname, WOW_PORT))
    {
      std::cerr << "Error while connecting to " << hostname << std::endl;
      return 1;
    }
  if (!s.send(WakeOnWan::createMagicPacket(mac)))
    {
      std::cerr << "Error while sending packet to " << hostname << std::endl;
      return 1;
    }
  std::cout << "Magic packet sent!" << std::endl;
  s.close();
  return 0;
}

std::string WakeOnWan::createMagicPacket(const std::string &mac)
{
  std::string	magic_packet;
  std::string	bmac;
  char*		macptr;
  char*		ptr;
  int		length;
  int		nb;

  for (int i = 0; i < 6; ++i)
    magic_packet += 0xff;
  length = mac.length();
  macptr = ::strdup(mac.c_str());
  ptr = macptr;
  for (int i = 0; i < 6; ++i)
    {
      nb = ::strtol(ptr, &ptr, 16);
      bmac += (char)nb;
      ptr++;
    }
  ::free(macptr);
  for (int i = 0; i < 16; ++i)
    magic_packet.append(bmac);
  return magic_packet;
}
